<?php
namespace Common\Logic;

/**
 * Class PayLogic 支付相关处理逻辑
 * @package Common\Logic
 */
class PayLogic
{
    /**
     * 创建微信支付所需的package
     */
    public function createWxpayPackage($payData)
    {
        vendor('WxPay.WxPayHelper');
        vendor('WxPay.WxPayUtil');
        try {
            if (empty($payData)
                or !isset($payData['lockname'])
                or !isset($payData['pay_id'])
                or $payData['paytotal'] <= 0
            ) {
                throw new \Exception('参数不正确');
            }


            $wxPayHelper = new \WxPayHelper();
            //* 付款金额
//            if ('testing' === APP_STATUS or 'dev' === APP_STATUS) {
//                $payData['paytotal'] = '1';
//            }
            //*/

            // 网关对于长度有限制
            $subject = $payData['lockname'];
            if (mb_strlen($subject, 'UTF-8') > 25) {
                $subject = mb_substr($subject, 0, 25, 'UTF-8');
                $subject .= '...';
            }
            //回调地址
            $wxPayHelper->setParameter("notify_url", C('SITE_URL') . 'notify/wxpay');

            // 订单名称
            $subject .= "[分享云商城]";


            $wxPayHelper->setParameter("body", $subject);
            $wxPayHelper->setParameter("out_trade_no", (string)$payData['pay_id']);
            $wxPayHelper->setParameter("total_fee", (string)$payData['paytotal']);
            $wxPayHelper->setParameter("spbill_create_ip", get_client_ip());
            $wxPayHelper->setParameter("time_start", date('YmdHis'));
            $wxPayHelper->setParameter("time_expire", $payData['pay_expire']);
            $wxPayHelper->setParameter("trade_type", "JSAPI");
            $wxPayHelper->setParameter("openid", $payData['openid']);
            $package = $wxPayHelper->create_biz_package();
//            log_message("createWxpayPackage", $package);
            return $package;
        } catch (\Exception $e) {
            $message = '创建微信支付包失败, #payData:' . json_encode($payData);
            log_message('wxpay-create-failed', $message, 'alert');
            return false;
        }
    }

    /**
     * 创建支付宝支付所需的form
     */
    public function createAlipayForm($payData)
    {
        vendor('AliWapPay.Corefunction');
        vendor('AliWapPay.MD5function');
        vendor('AliWapPay.Notify');
        vendor('AliWapPay.Submit');

        $alipay_config = C('ALIPAY_CONFIG');
        if (!isset($alipay_config)) {
            return false;
        }

        // 固定参数
        $format = "xml";
        $v = "2.0";
        $seller_email = $alipay_config['seller_email'];

        // 定义参数
        $req_id = date('Ymdhis');   // 请求号
        $pay_id = $payData['pay_id'];
        $lockname = urldecode($payData['lockname']);
        $total_fee = $payData['paytotal'] ;
        $pay_expire = (isset($payData['pay_expire']) and intval($payData['pay_expire']) > 0) ? (int)$payData['pay_expire'] : 3600 * 24;

        // 回调相关
         $notify_url = C('SITE_URL') . "notify/alipay";
         $call_back_url = C('SITE_URL') . "notify/alipayreturn";  // 页面跳转同步通知页面路径 不允许加?id=123这类自定义参数
         $merchant_url = C('SITE_URL') . "order/index"; // 操作中断返回地址 不允许加?id=123这类自定义参数

         // 订单名称
         $subject = $lockname . "-" . "[分享云商城]";



//        if ('testing' === APP_STATUS or 'dev' === APP_STATUS) {
//            $total_fee = 0.01;
//        }


        // 支付宝不允许 < > &
        // $subject = "1~!@#%^*()-_+ = &amp;< <> >";
        $subject = strip_tags($subject);
        $subject = str_replace('&', 'AND', $subject);
        if (mb_strlen($subject, 'UTF-8') > 50) {
            $subject = mb_substr($subject, 0, 50, 'UTF-8');
            $subject .= '...';
        }

        // 请求业务参数详细
        $req_data = '<direct_trade_create_req>
        <notify_url>' . $notify_url . '</notify_url>
        <call_back_url>' . $call_back_url . '</call_back_url>
        <seller_account_name>' . $seller_email . '</seller_account_name>
        <out_trade_no>' . $pay_id . '</out_trade_no>
        <subject>' . $subject . '</subject>
        <total_fee>' . $total_fee . '</total_fee>
        <merchant_url>' . $merchant_url . '</merchant_url>
        <pay_expire>' . $pay_expire . '</pay_expire>
        </direct_trade_create_req>';

        // 构造要请求的参数数组，无需改动
        $para_token = array(
            "service" => "alipay.wap.trade.create.direct",
            "partner" => trim($alipay_config['partner']),
            "sec_id" => trim($alipay_config['sign_type']),
            "format" => $format,
            "v" => $v,
            "req_id" => $req_id,
            "req_data" => $req_data,
            "_input_charset" => trim(strtolower($alipay_config['input_charset']))
        );

        // 建立请求
        $alipaySubmit = new \AlipaySubmit($alipay_config);
        $html_text = $alipaySubmit->buildRequestHttp($para_token);
        $html_text = urldecode($html_text);

        // 解析远程模拟提交后返回的信息
        $para_html_text = $alipaySubmit->parseResponse($html_text);
        if (isset($para_html_text['res_error'])) {
            $message = '创建支付宝表单可能失败了, #para_html_text:' . json_encode($para_html_text) . ';#paramToken' . json_encode($para_token) . ';#htmlText' . json_encode($html_text);
            log_message('alipay-parseResponse-failed', $message, 'alert');
            return false;
        }

        // 获取request_token
        $request_token = $para_html_text['request_token'];

        // 业务详细
        $req_data = '<auth_and_execute_req><request_token>' . $request_token . '</request_token></auth_and_execute_req>';

        // 构造要请求的参数数组，无需改动
        $parameter = array(
            "service" => "alipay.wap.auth.authAndExecute",
            "partner" => trim($alipay_config['partner']),
            "sec_id" => trim($alipay_config['sign_type']),
            "format" => $format,
            "v" => $v,
            "req_id" => $req_id,
            "req_data" => $req_data,
            "_input_charset" => trim(strtolower($alipay_config['input_charset']))
        );

        // 建立请求
        $alipaySubmit = new \AlipaySubmit($alipay_config);
        $html_text = $alipaySubmit->buildRequestForm($parameter, 'get', '确认');
        return $html_text;
    }

    /**
     * 设置支付单已支付
     * @param $payID
     * @param $out_trade_no
     * @param array $orderAppendParam
     * @return array|bool
     */
    public function setPaymentPaid($payID, $out_trade_no, $orderAppendParam = array())
    {
        $payModel = new \Common\Model\PayModel();
        $orderMdl = new \Common\Model\LockorderModel();

        $orderInfo = $orderMdl->getOrderInfo($payID);
//        log_message("paylogic", var_export($userInfo, true) . var_export($payInfo, true), 'alert');
        if (empty($orderInfo) or !isset($orderInfo['paystatus'])) {
            log_message('gateway-notify', '网关通知到了, 但是没查询到相关支付单:' . $payID, 'alert');
            return false;
        }



        if ($orderInfo['paystatus'] == '0') {
            // 更新订单支付状态和 添加支付宝订单信息
            $paidParam = array('paystatus' => '1', 'out_trade_no' => $out_trade_no);
            $orderAppendParam['order_id'] = $payID;
            //因为微信支付金额单位是分
            if('wxpay' == $orderAppendParam['gateway']){
                $orderAppendParam['gateway_total_fee'] = $orderAppendParam['gateway_total_fee']/100;
            }
            $set = array_merge($paidParam, $orderAppendParam);
            $payModel->savePays($set);

            // TODO 计算价格后再设置order的状态
            $orderParam = array(
                'paystatus' => '1'
            );
            $orderMdl->where("id={$payID}")->save($orderParam);


            //发短信内容整理存库
            $Lock = M('locktable');
            $locklist = $Lock->select();

            $content = "您已成功预订";
            $orders =  explode('@',$orderInfo['orderdata']) ;
//            orderdata:lockid-左右规格-内外规格-购买数量-单价
            foreach ($orders as $order) {
                $arr = explode('-',$order) ;
                if($arr[0] == '666' || $arr[0] == '777'){//网关 取电盒没左右内外规格
                    $content =  $content.'【'.getLockname($locklist,$arr[0])
                        .'，'.$arr[3].'个】';
                }else{
                    $content =  $content.'【'.getLockname($locklist,$arr[0])
                        .'，'.$arr[1].'，'.$arr[2].'，'.$arr[3].'把】';
                }


            }

//            if(strlen($content) >= 30){
//                $content = substr($content, 0,29).'……';
//            }

            $content = str_replace("left","左开",$content);
            $content = str_replace("right","右开",$content);
            $content = str_replace("in","内开",$content);
            $content = str_replace("out","外开",$content);

            $content = $content.'，我们将在30个工作日内为您配送，如有问题，请联系客服：0592-5793308 安装咨询，请联系：183-5429-8152';

//            您已成功预订芝麻云锁X600，左开，内开，1把，我们将在30个工作日内为您配送
//如有问题，请联系客服：0592-5793308；安装咨询，请联系：183-5429-8152
            $tmpMsg = array(
                'orderid' => $payID,
                'toname' => $orderInfo['username']
            );

             sendSingleSMS($orderInfo['userphone'],$content,$tmpMsg);

            return true;
        } else {
            // 不是未支付状态, 不处理
            return true;
        }
    }

    /**
     * 查询微客栈订单详细
     * @param $data
     */
    public function getWkzBillByDate($data)
    {
        $result = array();
        //获取微客栈订单明细
        $PayMdl = new \Common\Model\PayModel();
        $result = $PayMdl->getWkzBillByDate($data);
        //获取微客栈订单的结算状态
        $BillMdl = new \Common\Model\WxBillModel();
        $con["innid"] = $data["innid"];
        $con["billdate"] = array('between', array($data["fromdate"], $data["enddate"]));
        $con['service'] = $data["service"];
        $billdata = $BillMdl->getBills($con);
        foreach ($result as $k => $v) {
            $result[$k]["accountstatus"] = 0;
            foreach ($billdata as $bk => $bv) {
                $addtime = date("Y-m-d", strtotime($v["addtime"]));
                if ($addtime == $bv["billdate"] && $v["gateway"] == $bv["gateway"]) {
                    $result[$k]["accountstatus"] = $bv["ispaid"];
                    if ($bv["paidon"] == "0000-00-00 00:00:00") {
                        $result[$k]["settletime"] = "-";
                    } else {
                        $result[$k]["settletime"] = $bv["paidon"];
                    }
                    break;
                }
            }
        }
        if (strlen($data["orderstatus"]) > 0) {
            foreach ($result as $k => $v) {
                if ($v["accountstatus"] != $data["orderstatus"]) {
                    unset($result[$k]);
                }
            }
        }
        // 重置数组的键值
        $result = array_merge(array(), $result);
        return $result;
    }

    /**
     * 设置支付单已支付
     * @param $payID
     * @param $out_trade_no
     * @param array $orderAppendParam
     * @return array|bool
     */
//    public function gotoplace($payID)
//    {
//        $payModel = new \Common\Model\PayModel();
//        $orderModel = new \Common\Model\WxOrderModel();
//        $userModel = new \Common\Model\WxUserModel();
//
//        $payInfo = $payModel->getPayInfoByPayID($payID);
//        $userInfo = $userModel->findByID($payInfo['wxuserid']);
//        if (empty($payInfo) or !isset($payInfo['pay_status'])) {
//            log_message('gateway-notify', '网关通知到了, 但是没查询到相关支付单:' . $payID, 'alert');
//            return false;
//        }
//
//        // 已支付, 未落单的才会去落单
//        if ($payInfo['pay_status'] === '1' and $payInfo["resmsg"] === "") {
//            // 获取订单的所有支付信息, 给云掌柜/云酒店
//            $remark = $couponNO =  $couInfo = $priceInfo = '';
//            $paidFee = $realPaidFee = $refundFee = 0;
//
//            $pays = $payModel->getPaysByOrderID($payInfo['order_id']);
//            $paytype = $paytypename = '';
//            foreach ($pays as $tmpPay) {
//                // 付款方式(全款/订金)
//                $pay_pattern = $tmpPay["pay_pattern"];
//
//                if ('coupon' === $tmpPay['pay_type']) {
//                    $couponNO = $tmpPay['coupon_no'];
//                    $remark .= '使用优惠券立减' . $tmpPay['fee'] / 100 . '元(券号' . $couponNO . ')';
//                    $couInfo = '(' . $payInfo['trueprice'] / 100 . '-' . $tmpPay['fee'] / 100 . ')';
//                    $priceInfo = $payInfo['trueprice'] / 100 - $tmpPay['fee'] / 100 < 0 ? 0 : $payInfo['trueprice'] / 100 - $tmpPay['fee'] / 100;
//                }
//                if ('discount' === $tmpPay['pay_type']) {
//                    $couponNO = $tmpPay['coupon_no'];
//                    $remark .= '使用折扣券立减' . ($tmpPay['fee'] - $tmpPay['needprice']) / 100 . '元(券号' . $couponNO . ');';
//                    $couInfo = '(' . $payInfo['trueprice'] / 100 . '-' . $tmpPay['fee'] / 100 . ')';
//                    $priceInfo = $payInfo['trueprice'] / 100 - $tmpPay['fee'] / 100 < 0 ? 0 : $payInfo['trueprice'] / 100 - $tmpPay['fee'] / 100;
//                }
//                if ('gateway' === $tmpPay['pay_type']) {
//                    $paidFee = $tmpPay['fee'];
//                    $refundFee = $tmpPay['gateway_total_fee'];
//                    $realPaidFee = $tmpPay['gateway_total_fee'];
//
//                    $paytype = $tmpPay['gateway'];
//                    if ($paytype == 'alipay') {
//                        $paytypename = '支付宝';
//                    } else if ($paytype == 'wxpay') {
//                        $paytypename = '微信支付';
//                    }
//
//                    if ($pay_pattern == "all") {
//                        $remark .= '已使用' . $paytypename . '支付全额房费' . $tmpPay['gateway_total_fee'] / 100 . '元';
//                    } else if ($pay_pattern == "every" || $pay_pattern == "first") {
//                        if ($pay_pattern === "first" and $payInfo['nights'] == 1) {
//                            $remark .= '已付全款' . $paidFee / 100 . '元';
//                        } else {
//                            $finaprice = $payInfo["trueprice"] - $tmpPay['gateway_total_fee'];
//                            $remark .= '已使用' . $paytypename . '支付订金' . $tmpPay['gateway_total_fee'] / 100 . '元，到店还需付' . $finaprice / 100 . '元';
//                        }
//                    }
//                }
//            }
//
//            /**
//             * 去落单
//             */
//            $sourcePlatform = '云掌柜版本';
//            if ($payInfo['orderkind'] == 'goods') {
//                $yzgData = array(
//                    'innid' => $payInfo['innid'],
//                    'goodsid' => $payInfo['roomtypeid'],
//                    'totalprice' => $payInfo['totalprice'],
//                    'num' => $payInfo['num'],
//                    'guestname' => $payInfo['guestname'],
//                    'guestphone' => $payInfo['guestphone'],
//                    'remark' => $payInfo['remark'],
//                    'paytypecode' => $paytype,
//                    'paytypename' => $paytypename,
//                );
//                $YinnServiceLogic = new \Common\Logic\YinnServiceLogic();
//                $orderResult = $YinnServiceLogic->saveGoodsOrder($yzgData, $payInfo['channelcode']);
//            } else {
//                $yzgData = array(
//                    'innid' => $payInfo['innid'],
//                    'roomtypeid' => $payInfo['roomtypeid'],
//                    'nights' => $payInfo['nights'],
//                    'fromdate' => $payInfo['arrivedate'],
//                    'coupon' => $couponNO,
//                    'trueprice' => $payInfo['trueprice'], // 打折后的价格
//                    'paidprice' => $paidFee,
//                    'roomnum' => $payInfo['num'],
//                    'guestname' => $payInfo['guestname'],
//                    'guestphone' => $payInfo['guestphone'],
//                    'remark' => $remark,
//                    'paytype' => $paytype,
//                    'paytypename' => $paytypename,
//                    'order_id' => $payInfo['order_id'], // 极端情况的时候, 网关发来俩支付通知, 这个为了让云掌柜不落两次
//                );
//                $YinnServiceLogic = new \Common\Logic\YinnServiceLogic();
//                $orderResult = $YinnServiceLogic->saveInnOrder($yzgData, $payInfo['channelcode']);
//            }
//
//            if ('success' === $orderResult['status']) {
//                // 云掌柜落单成功
//                $yzgSet = array(
//                    'resmsg' => 'success',
//                    'statussummary' => 'placed',
//                    'outorderid' => $orderResult['orderid']
//                );
//                $orderModel->where("id={$payInfo['order_id']}")->save($yzgSet);
//
//                // wechat PUSH
//                $datearr = explode("-", $payInfo["arrivedate"]);
//                $datestr = $datearr[0].'年'.$datearr[1].'月'.$datearr[2].'日';
//                $leavedatestr =  date('Y年m月d日', strtotime('+'.$payInfo['nights'].' days', strtotime($payInfo["arrivedate"])));
//                $goodsdate = date('Y年m月d日H:i');
//
//                $data = array(
//                    "innname" => $payInfo['innname'],
//                    "innaddress" => $payInfo['innaddress'],
//                    "trueprice" => ($payInfo['trueprice'] / 100),
//                    "innphone" => $payInfo['innphone']
//                );
//                if ($payInfo['orderkind'] == 'goods') {
//                    $data["goodsname"] = $payInfo['roomname'];
//                    $data["date"] = $goodsdate;
//                    $templateType = 'GOODS_ORDER_SUCCESS';
//                } else {
//                    $data["guestname"] = $payInfo['guestname'];
//                    $data["roominfo"] = $payInfo['roomname'] . "，" . $payInfo['num'] . "间";
//                    $data["date"] = $datestr . "入住，" . $leavedatestr . "离店，住" . $payInfo['nights'] . "晚";
//                    if ($realPaidFee > 0) {
//                        $data["trueprice"] = $realPaidFee / 100;
//                    }
//                    if ($priceInfo) {
//                        $data["trueprice"] = $priceInfo . $couInfo;
//                    }
//
//                    $templateType = 'ROOM_ORDER_SUCCESS';
//                }
//                $WxTemplatesModel = new \Weiinn\Model\WxTemplatesModel();
//                if(!$res = $WxTemplatesModel->addTemplatesInfo($userInfo['openid'], $data, $templateType)) {
//                    log_message('sendtemplates-ERROR', 'orderSuccess');
//                }
//
//                return true;
//            } else if ($orderResult['status'] == 'fail'){
//                // 不同支付方式退款单的参数: 自动退款和人工退款的不同
//                $refundStatus = 'waiting';
//                $answerTime = '';
//                $createReason = '落单失败';
//                // TODO 如果是微信支付，并且有明确的落单失败，则accepted自动退款，否则waiting后台确认
////                if ('wxpay' === $paytype and true === $orderResult['autoRefund']) {
////                    $refundStatus = 'accepted';
////                    $answerTime = date('Y-m-d H:i:s');
////                    $createReason = '落单失败并自动退款';
////                }
//
//                // 退款单i
//                $refundTmp = array(
//                    'orderid' => $payInfo['order_id'],
//                    'pay_id' => $payInfo['pay_id'],
//                    'paidtotal' => $refundFee,
//                    'refundneed' => $refundFee,
//                    'refundstatus' => $refundStatus,
//                    'gatewaystatus' => 'waiting',
//                    'createreason' => $createReason,
//                    'createon' => date('Y-m-d H:i:s'),
//                    'answeron' => $answerTime,
//                    'createby' => 'system',
//                    'answerby' => 'system',
//                );
//
//                if ($payInfo['orderkind'] == 'goods') {
//                    $refundTmp['orderdesc'] = $payInfo['innname'] . ',' . $payInfo['roomname'] . ',' . $payInfo['num'] . '件';
//                } else {
//                    $refundTmp['orderdesc'] = $payInfo['innname'] . ',' . $payInfo['roomname'] . ',' . $payInfo['arrivedate'] . '入住, 住' . $payInfo['nights'] . '晚';
//                }
//
//                $refundModel = new \Common\Model\RefundModel();
//                $id = $refundModel->add($refundTmp);
//                if (!$id) {
//                    log_message('save-refund-failed', $refundTmp, 'alert');
//                }
//                //\
//
//                $tmpStatusSummary = $refundStatus === 'accepted' ? 'refunded' : 'failed';
//                $failSet = array(
//                    'resmsg' => 'fail',
//                    'statussummary' => $tmpStatusSummary,
//                    'restype' => isset($orderResult['errorcode']) ? $orderResult['errorcode'] : '',
//                    'resdesc' => isset($orderResult['msg']) ? $orderResult['msg'] : '';
//                );
//                $orderModel->where("id={$payInfo['order_id']}")->save($failSet);
//
//                //* wechat PUSH
//                $refund_data['orderdesc'] = $refundTmp['orderdesc'];
//                $WxTemplatesModel = new \Weiinn\Model\WxTemplatesModel();
//
//                if(!$res = $WxTemplatesModel->addTemplatesInfo($userInfo['openid'], $refund_data, 'SAVE_REFUND_FAILED')) {
//                    log_message('send-wxmsg-failed', 'refund');
//                }
//                //*/
//
//                // 邮件
//                $contentHtml = '落单失败了, 请迅速解决, 退款单ID:' . $id .
//                    '<br/>订单信息:' . $refundTmp['orderdesc'] .
//                    '<br/>可能的失败原因:' . $orderResult['msg'];
//                $mailLogic = new \Common\Logic\MailLogic();
//                $mailres = $mailLogic->addMailQueue(APP_STATUS . ';' . 'AUTO: (' . $sourcePlatform . ')落单失败了!!!', $contentHtml, C('DEV_MAIL_GROUP'), 'robot');
//                if(!$mailres or $mailres['status'] == 'invalid'){
//                    log_message('addmail-ERROR', 'msg: '.$mailres['status']);
//                }
//
//                return true;
//            }
//        } else {
//            echo "not paid status";
//        }
//    }

}


// end
